package com.study.tiger.util;

import com.study.tiger.pojo.BaseTree;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Message: 构造树结构
 * @Author: Tiger
 * @Version: V1.0
 */
public class TreeUtil {

    public static <T extends BaseTree> List<T> testPredicate(List<T> list, Predicate<T> predicate){
        // 获取全部的父节点
        List<T> parentList = new ArrayList<>();
        for(T baseTree:list){
            if (predicate.test(baseTree)){
                parentList.add(baseTree);
            }
        }
        // 获取全部的子节点
        List<T> childrenLists = new ArrayList<>();
        for (T baseTree:list){
            if(!predicate.test(baseTree)){
                childrenLists.add(baseTree);
            }
        }
        // 构建树
        return buildTree(parentList,childrenLists);
    }

    private static <T extends BaseTree> List<T> buildTree(List<T> parentList,List<T> childrenList){
        for (T baseTree1:parentList){
            List<T> childrenListTemp = new ArrayList<>();
            for(T baseTree:childrenList){
                if(baseTree.getPid().equals(baseTree1.getId())){
                    childrenListTemp.add(baseTree);
                }
            }
            baseTree1.setChildren((List<BaseTree>) childrenListTemp);
            if(childrenListTemp.size()!=0){
                buildTree(childrenListTemp,childrenList);
            }
        }
        return parentList;
    }
}
